package itpenguin.review;

import itpenguin.common.PMFactory;
import itpenguin.review.entities.Item;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamException;

public class RefreshServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		PersistenceManager pm = PMFactory.getInstance().getPersistenceManager();
		Query query = pm.newQuery("select count(this) from itpenguin.review.entities.Item ");
		long all = (Long)query.execute();
		
		int target = (int)(all * 0.03) + 1;
		
		query = pm.newQuery("select from itpenguin.review.entities.Item order by cachedDate asc"); 
		query.setRange(0, target);
		List<Item> refreshList = (List<Item>) query.execute();
		for(Item item : refreshList) {
			try {
				item.updateItemInfo();
				item.updateYear();
			} catch (XMLStreamException e) {
				throw new ServletException(e);
			}
			try {
				Thread.sleep(800);
			} catch (InterruptedException e) {
				throw new ServletException(e);
			}
		}
		
		pm.close();
	}

}
